package com.aier.entrance.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;

import com.aier.common.common.Constant;
import com.aier.common.common.ImageUtil;
import com.aier.entrance.common.EntranceServerData;

public class Snapshot extends Thread {

    private String urlStr;
    private String user;
    private String pwd;
    private String filepath;
    private short supplier;
    
    /**
     * @param supplier
     *            提供商
     * @param urlStr
     *            目的IP
     * @param user
     *            用户名
     * @param pwd
     *            密码
     * @param filepath
     *             上传路径
     */
    public Snapshot(short supplier,String urlStr, String user, String pwd,
            String filepath) {
        this.supplier = supplier;
        this.urlStr = urlStr;
        this.user = user;
        this.pwd = pwd;
        this.filepath = filepath;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        if(supplier == EntranceServerData.VIDEO_WS){
            try {
                String trueUrl = urlStr + "/snapshot.cgi?user=" + user + "&pwd="
                        + pwd;
                System.out.println(trueUrl+",filepath:"+filepath);
                URL url = new URL(trueUrl);
                URLConnection urlCon = url.openConnection();
                HttpURLConnection httpUrlCon = (HttpURLConnection) urlCon;
                httpUrlCon.setRequestMethod("GET");
                httpUrlCon.connect();
                InputStream in = httpUrlCon.getInputStream();
    //            System.out.println("拍完照时间" + new Date().getTime());            
                //将图片写入文件夹 
                writeToFileFromServer(in);
                in.close();
                httpUrlCon.disconnect();
                int ind = filepath.lastIndexOf("/");
                String dir_path = filepath.substring(0,ind+1);
                String picname = filepath.substring(ind+1);
                String flag = ImageUtil.compressPic_card(dir_path, picname, Constant.num_30, Constant.num_30, true,"small");
                if ("no".equals(flag)) {
                    System.out.println("获取摄像头照片失败！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(supplier == EntranceServerData.VIDEO_HK){
            String[] url = urlStr.split(":");
            String ip = url[1].substring(2);
            HttpHost targetHost = new HttpHost(ip, Integer.parseInt(url[2]));               
            DefaultHttpClient client = new DefaultHttpClient();                
            BasicHttpContext context = new BasicHttpContext();  
            context.setAttribute(ClientContext.CREDS_PROVIDER, new BasicCredentialsProvider());
            CredentialsProvider provider = (CredentialsProvider)context.getAttribute(ClientContext.CREDS_PROVIDER);
            provider.setCredentials(new AuthScope(targetHost.getHostName(),
                    targetHost.getPort()),new UsernamePasswordCredentials("admin", "12345")); 
            HttpGet get = new HttpGet(urlStr + "/Streaming/channels/1/picture" +
                    "?snapShotImageType=JPEG&videoResolutionWidth=680&videoResolutionHeight=480");
            HttpResponse response;
            try {
                response = client.execute(get,context);
                HttpEntity entity = response.getEntity();  
                System.out.println("拍完照时间" + new Date().getTime());        
                writeToFileFromServer(entity.getContent());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        
    }
    /**
     *     
     * @param in    输入流
     *                 将图片写入文件夹
     */
    public void writeToFileFromServer(InputStream in){
        try{

            FileOutputStream out = new FileOutputStream(new File(filepath));
            int i = 0;
            while ((i = in.read()) != -1) {
                out.write(i);
            }
            out.close();        
    //            System.out.println("上传完毕时间" + new Date().getTime());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public String getUrlStr() {
        return urlStr;
    }

    public void setUrlStr(String urlStr) {
        this.urlStr = urlStr;
    }

}
